const gulp=require('gulp');
const browserSync=require('browser-sync');
const reload=browserSync.reload;
const csso=require('gulp-csso');
const rename=require('gulp-rename');
const uglify=require('gulp-uglify');
const babel=require('gulp-babel');
const greplace=require('gulp-replace');
const fs=require('fs');

gulp.task('watch',function(){

    browserSync({
        server:{
            baseDir:'src'
        },
        port:9527,
        open:false,
        /*
        proxy:'https://wxdev.xuyanzhe.cn',
        serveStatic:['src']*/
    });

    gulp.watch(['./src/**/*.html','./src/**/*.css','./src/**/*.js'],reload);
});

gulp.task('build',function(){
    let hash=Math.random().toString(16).substring(2);

    if (!fs.existsSync('./dist')){
        fs.mkdirSync('./dist')
    }

    for (let item of fs.readdirSync('./dist'))
    {
        fs.unlinkSync(`./dist/${item}`);
    }

    
    gulp.src('./src/**/*.js')
    .pipe(babel({
        presets:['@babel/env']
    }))
    .on('error',function(e){console.log(e)})
    .pipe(uglify())
    .on('error',function(e){console.log(e)})
    .pipe(rename({
        suffix:`.${hash}`
    }))
    .pipe(gulp.dest('./dist/'));

    gulp.src('./src/**/*.css')
    .pipe(csso({
        restructure: false,
        sourceMap: false,
        debug: false
    }))
    .pipe(rename({
        suffix:`.${hash}`
    }))
    .pipe(gulp.dest('./dist/'));

    gulp.src('./src/**/*.html')
    .pipe(greplace(/<script.*>.*<\/script>/g,function(match){
        
        let repstr='';
        let s2=match.substr(match.indexOf("src=")+5,2)
        if (s2==="ht" || s2==="//")
        {
            repstr=match.replace('.js','.min.js');
        }else{
            repstr=match.replace('.js',`.${hash}.js`);
        }
        return repstr;
    }))
    .pipe(greplace(/<link.*>/g,function(match){
        let repstr='';
        let s2=match.substr(match.indexOf("href=")+6,2)
        if (s2==="ht" || s2==="//")
        {
            repstr=match.replace('.css','.min.css');
        }else{
            repstr=match.replace('.css',`.${hash}.css`);
        }
        return repstr;
    }))
    .pipe(gulp.dest('./dist/'));
});